﻿var logoItemHtml = '' + '<div class="col-xs-3"><img class = "logoItem" src="{src}" />' + '</div>';
var url_toutiao = '';   //即将过时 07-26
var url_source = '';    //站内URL，一般用来显示排版出问题的外链

$(function () {
    loadSource();
    bindLogoUpload();
    $("#subBtn").on("click", submit);
});

// 解析源代码
function loadSource() {
    var url = getQueryString("url");
    if (url == null || url.length == 0) {
        Alert("没用可用的网址");
        return;
    }
    
    // 微信订阅号文章、今日头条 单独处理
    if (url.indexOf("://mp.weixin.qq.com")>0) {
        loadWxUrl(url);
    } else if (url.indexOf("v.qq.com") > -1) {
        loadQQVideo(url);
    }
    else if (url.indexOf("http://url.cn/") > -1) {
        loadUrlCN(url);
    } else if (url.indexOf("toutiao.com") > -1 || url.indexOf("pstatp.com") > -1 || url.indexOf("http://url.cn/") > -1) {
        loadTouTiao(url);
        loadInfo(url);
    }
    else if (url.indexOf("xw.qq.com") > -1) {
        loadPage(url);
        loadInfo(url);
    }
    else {
        $(".iframe-body").append("<iframe src = '" + url + "'></iframe>");
        initIfm();
        loadInfo(url);
    }
}

//获取网络标题图片等信息
function loadInfo(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetEditInfo", {
        url: url
    },
        fillData, "json");
}

//处理返回的数据
function fillData(data) {
    wait.dismiss();
    if (data.code != 0) {
        wait.show(data.msg);
        return;
    }
    $("#title").val(data.item.title);

    // 默认第一张图片为头图
    if (data.item.imgList.length > 0) {
        $(".logo").attr("src", data.item.imgList[0]);
    }
    $(data.item.imgList).each(function () {
        $("#imgList").append(logoItemHtml.replace(/{src}/, this));
    });

    // 候选图片点击事件
    $(".logoItem").off("click");
    $(".logoItem").on("click", function () {
        $(".logo").attr("src", $(this).attr("src"));
    });
}

function initIfm() {
    var wh = $(window).height(); // 当前网页课件区域高度
    var iframeTop = $(".iframe-body iframe").offset().top; // 框架距顶部的距离
    $(".iframe-body iframe").css("height", wh - iframeTop + "px"); // 把iframe全屏显示
}

// 绑定logo图片上传
function bindLogoUpload() {
    // 标题logo
    $("#logoFile")
			.fileinput(
					{
					    showUpload: false,
					    showCaption: false,
					    showPreview: false,
					    browseLabel: '',
					    browseClass: "",
					    removeClass: "hide",
					    browseIcon: '<button id = "btnUploadLogo"  class="btn btn-default btn-block">上传logo</button>',
					    fileType: "any",
					    allowedFileExtensions: ['jpg', 'png', 'gif', 'bmp',
								'jpeg']
					});

    var userAgent = navigator.userAgent.toLocaleLowerCase();
    if (userAgent.indexOf("wjx") != -1 && userAgent.indexOf("android") != -1) {

        //客户端
        $("#logoFile").hide();

        $("#btnUploadLogo").on("click", function () {
            var param = { cutType: 1, width: 300, height: 300, callback: "resetLogo", url: "http://" + window.location.host + "/Client/Ajax/Upload.ashx?Img" };
            var p = JSON.stringify(param);
            window.location.href = "callback://imageUpload?" + p;
            return false;
        });
    }
    else {
        // 选择了图片提交图片
        $("#logoFile").change(function () {
            if ($(this).val().length == 0) {
                toast.show("文件格式错误");
                return;
            }
            wait.show();

            //选择好文件后提交表单
            $("#logoUpload").ajaxSubmit({
                type: 'post',
                dataType: "json",
                url: '/Client/Ajax/Upload.ashx?Img&is_cut=1&width=300&height=300',
                success: function (data) {
                    wait.dismiss();
                    if (data.code == 0) {
                        resetLogo(data.item);
                    }
                    else {
                        toast.show(data.msg);
                    }
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                    wait.dismiss();
                    $(".logo").val("");
                    toast.show("图片文件太大或文件格式不正确");
                }
            });
        });
    }
}

function resetLogo(src) {
    $(".logo").attr("src", src);
    $("#imgList").append(logoItemHtml.replace(/{src}/, src));

    // 候选图片点击事件
    $(".logoItem").off("click");
    $(".logoItem").on("click", function () {
        $(".logo").attr("src", $(this).attr("src"));
    });
}

//绑定提交事件
function submit() {
    var title = $("#title").val();
    var url = getQueryString("url");
    if (title.length == 0) {
        toast.show("标题不能为空");
        return;
    }

    var logo = $(".logo").attr("src");
    if (logo == "img/default.png") {
        toast.show("请设置一张分享logo");
        return;
    }
    if (url_source != "")
        url = url_source;
    var ec = encodeURIComponent;
    window.location.href = "to_detail.aspx?type=2&title=" + ec(title) + "&logo=" + ec(logo) + "&url=" + ec(url);
}


//微信链接处理
function loadWxUrl(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            loadInfo(url);
            window.ifm = data.item;
            $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'javascript:parent.ifm'></iframe>");
            initIfm();
            ifmLoad();
        }
        else {
            toast.show(data.msg);
        }

    }, "json");
}

//今日头条处理
function loadTouTiao(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url, "isinfo": 1 }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            var url = "";

            var item = data.item;
            if (item.url != null)
                url = item.url;        //默认网址
            if (item.return_url != null && item.return_url != "")
                url = item.return_url; //最后显示的网址
            console.log(item);

            if (url.indexOf("toutiao.com") > -1 || url.indexOf("utm_medium=toutiao") > -1) {
                url_source = shared_domain + "/client/page/toutiao.aspx?source_id=" + item.id;
                $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'page/toutiao.aspx?source_id=" + item.id + "'></iframe>");
            }
            else
                $(".iframe-body").append("<iframe id = 'ifmUrl' src = '" + url + "'></iframe>");
            initIfm();
        }
        else {
            toast.show(data.msg);
        }

        
    }, "json");
}

//url.cn 短域名处理
function loadUrlCN(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url, "isinfo": 1 }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            var url = "", oldUrl = "";

            var item = data.item;
            if (item.url != null) {
                url = item.url;
                oldUrl = item.url;     //粘贴的网址
            }
            if (item.return_url != null)
                url = item.return_url; //重定向后的网址

            //对重定向的网址做处理

            //微信链接处理
            if (url.indexOf("http://mp.weixin.qq.com") > -1) {
                loadInfo(oldUrl);
                url_source = url;
                window.ifm = item.source;
                $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'javascript:parent.ifm'></iframe>");
                initIfm();
                ifmLoad();
            }
            else if (url.indexOf("toutiao.com") > -1) {
                //头条链接处理
                url_source = shared_domain + "/client/page/toutiao.aspx?source_id=" + item.id;
                $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'page/toutiao.aspx?source_id=" + item.id + "'></iframe>");
            }
            else {
                $(".iframe-body").append("<iframe src = '" + url + "'></iframe>");
                initIfm();
                //loadInfo(url);
            }
        }
        else {
            toast.show(data.msg);
        }
    }, "json");
}

function loadPage(url) {
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url, "isinfo": 1 }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            var url = "";
            if (data.item.url != null)
                url = data.item.url;        //默认网址
            if (data.item.return_url != null)
                url = data.item.return_url; //最后显示的网址
            $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'page/qq.aspx?source_id=" + data.item.id + "'></iframe>");
            url_source = shared_domain + "/client/page/qq.aspx?source_id=" + data.item.id;
            initIfm();
            
        }
        else {
            toast.show(data.msg);
        }
    }, "json");
}

function loadQQVideo(url) {
    url = formatQQUrl(url);
    wait.show();
    $.post("/Client/Ajax/HttpSource.ashx?GetSource", { url: url, "isinfo": 1 }, function (data) {
        wait.dismiss();
        if (data.code == 0) {
            url_source = shared_domain + "/client/page/qq.aspx?source_id=" + data.item.id;
            $(".iframe-body").append("<iframe id = 'ifmUrl' src = 'page/qq.aspx?source_id=" + data.item.id + "'></iframe>");
            initIfm();
        }
        else {
            toast.show(data.msg);
        }
    }, "json");
}

function ifmLoad() {
    setTimeout(function () {
        //解决ios微信链接内容显示不全Bug
        if ($("#ifmUrl").attr("src").indexOf("http") != 0 && navigator.userAgent.toLowerCase().indexOf("iphone os") != -1) {
            $("#ifmUrl").contents().find("body").css("width", $(window).width() + "px");
        }

        $("#ifmUrl").contents().find("[data-src]").each(function () {
            $(this).attr("src", $(this).attr("data-src"));
        });

        reloadWxVideo();
    }, 500);
}

function formatQQUrl(url) {
    if (url.indexOf("//v.qq.com") > -1) {
        if (url.indexOf("//v.qq.com/x/page") > -1) {
            var newUrl = "https://m.v.qq.com/page/7/X/6/";
            var htmlName = "";
            if (url.lastIndexOf("/") > -1)
                htmlName = url.substring(url.lastIndexOf("/") + 1);
            url = newUrl + htmlName;
        }
        else {
            url = url.replace("http://", "https://");
            url = url.replace("//v.qq.com", "//m.v.qq.com");
            url = url.replace("/x/cover/", "/cover/k/");
            url = url.replace(".com/prev/", ".com/cover/");
        }
    }
    return url;
}